package tt.dz.service.imp.sys;

import javax.annotation.Resource;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.BucketManager;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;

import java.io.UnsupportedEncodingException;
import java.util.*;

import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import tt.dz.dao.ext.base.OmsStoreFileDao;
import tt.dz.entity.base.JsonForList;
import tt.dz.entity.base.OmsStoreFile;
import tt.dz.entity.station.OmsStation;
import tt.dz.service.sys.QiniuService;
import tt.dz.util.StringUtil;

@Service @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
public class QiniuServiceImpl implements QiniuService {

	@Resource
	OmsStoreFileDao  omsStoreFileDao;
	
	 //设置好账号的ACCESS_KEY和SECRET_KEY
//	  String ACCESS_KEY = "PtUqeP3qvMiKnxvz8UCUri4mpySsxAhMo5ciElM3";
//	  String SECRET_KEY = "W9nTDUNRDIm-LJVpRcV6CVzwLJT6CikVd3gxoBT9";
//	  String DOMAIN = "http://7xt6wn.com1.z0.glb.clouddn.com/";
	  
//	  String ACCESS_KEY = "fLNVq6AUMYzBLkgUUTRZ-uV6skBrei3tmCH0DJB1";
//	  String SECRET_KEY = "qWfgmN4L9fzuC3YPL9vUgSYtBmdQn5ScxOaUTjWo";
//	  String DOMAIN = "http://o99hfsxmo.bkt.clouddn.com/";
	  //要上传的空间
//	  String bucketname = "dianzhuang";
	  
	  
	  @Value(value="${qiniuAccessKey}")
	  String ACCESS_KEY;
	  @Value(value="${qiniuSecretKey}")
	  String SECRET_KEY;
	  @Value(value="${qiniuDomain}")
	  String DOMAIN;
	  @Value(value="${qiniuBucketName}")
	  String bucketname;
	  
	  //上传到七牛后保存的文件名
	  //String key = "my-java.png";
	  //上传文件的路径
	  //String FilePath = "/.../...";

	  //密钥配置
	  //Auth auth = Auth.create(ACCESS_KEY, SECRET_KEY);
	  //创建上传对象
	  //UploadManager uploadManager = new UploadManager();
	  //实例化一个BucketManager对象
	  //BucketManager bucketManager = new BucketManager(auth);
	  //简单上传，使用默认策略，只需要设置上传的空间名就可以了
	  
	  
	  
	 //密钥配置
	  Auth auth;
	  //创建上传对象
	  UploadManager uploadManager = new UploadManager();
	  //实例化一个BucketManager对象
	  BucketManager bucketManager;
	  //简单上传，使用默认策略，只需要设置上传的空间名就可以了

	//获取上传Token
    @Override
    public String getUpToken(){
    	auth = Auth.create(ACCESS_KEY, SECRET_KEY);
    	String upToken = auth.uploadToken(bucketname);
        return upToken;
    }
	  
    //上传到七牛云服务空间
	@Override
	public boolean upload(String filePath,String key) {
		 
	    try {
	      //调用put方法上传
	      Response res = uploadManager.put(filePath, key, getUpToken());
	      //打印返回的信息
	      System.out.println(res.bodyString()); 
	      } catch (QiniuException e) {
	          Response r = e.response;
	          // 请求失败时打印的异常的信息
	          System.out.println(r.toString());
	          
	          try {
	              //响应的文本信息
	            System.out.println(r.bodyString());
	          } catch (QiniuException e1) {
	              //ignore
	        	  return false;
	          }
	          
	          return false;
	      }       
		
		return true;
	}
	
	//删除七牛云服务空间的文件
	@Override
	public boolean delete(String key) {		 
		 try {
			  auth = Auth.create(ACCESS_KEY, SECRET_KEY);
			  bucketManager = new BucketManager(auth);
		      //调用delete方法移动文件
		      bucketManager.delete(bucketname, key);
		 } catch (QiniuException e) {
		      //捕获异常信息
		      Response r = e.response;
		      System.out.println(r.toString());   
		      try {
	              //响应的文本信息
	            System.out.println(r.bodyString());
	          } catch (QiniuException e1) {
	              //ignore
	        	  return false;
	          }
	          
	          return false;
		 }
		return true;
	}
	
	//获取该文件七牛云的下载路径
	@Override
	public String download(String key){
		auth = Auth.create(ACCESS_KEY, SECRET_KEY);
		//调用privateDownloadUrl方法生成下载链接,第二个参数可以设置Token的过期时间
		String URL = DOMAIN + key;
		String downloadRUL = auth.privateDownloadUrl(URL,3600);
		//System.out.println(downloadRUL);
		return downloadRUL;
	}
	
	//获取该实体所有归属文件
	@Override
	public List<OmsStoreFile> getOmsStoreFileList(String entity_tbl, String entity_id,String remote_file_names) {
		StringBuilder sb = new StringBuilder("where valid_flag = 1 and entity_tbl = ");
		sb.append("'"+entity_tbl+"' and entity_id = ");
		sb.append("'"+entity_id+"' ");
		if (StringUtil.isNotBlank(remote_file_names)) {
			String[]  list =  remote_file_names.split(",");
			if(list.length>0){
				sb.append("and remote_file_name in (");
				for(String str :list){
					try {
						sb.append("'"+new String(str.getBytes("iso-8859-1"),"utf-8")+"',");
					} catch (UnsupportedEncodingException e) {
						e.printStackTrace();
					}
					
				}
				sb.deleteCharAt(sb.length()-1);
				sb.append(") ");
			}
		}
		OmsStoreFile omsStoreFile = new OmsStoreFile();
		return (List<OmsStoreFile>) omsStoreFileDao.findListByCondition(omsStoreFile, sb.toString());
	}
	
	//保存实体到本地数据库
	@Override
	public void saveOmsStoreFile(List<OmsStoreFile> omsStoreFileList) {
		omsStoreFileDao.saveList(omsStoreFileList);	
	}
	
	//逻辑删除该上传实体
	@Override
	public void logicDelete(OmsStoreFile omsStoreFile) {
		omsStoreFileDao.LogicDeleteObject(omsStoreFile);		
	}

	@Override
	public String getRemoteFileNames(String entity_tbl, String entity_id) {
		String sql = "select group_concat(a.remote_file_name) remoteFileNames from oms_store_file a "
				    +"where  a.entity_tbl='" + entity_tbl + "' and a.entity_id='" + entity_id + "' and a.valid_flag=1";
		List<Map<String, Object>> listRemoteFileNames = omsStoreFileDao.findDataBySql(sql, null);
		if (listRemoteFileNames.size()>0) {
			Map<String, Object> mapRemoteFileNames = listRemoteFileNames.get(0);
			return mapRemoteFileNames.get("remoteFileNames") == null ? null:mapRemoteFileNames.get("remoteFileNames").toString();
		}
		return null;
	}

}
